from flask import Flask, jsonify, request
from flask_cors import CORS  # 解决跨域问题
from src.db.operations import (
    register_user, authenticate_user, get_user_by_username,
    create_artwork, get_all_artworks
)
import logging

# 初始化Flask应用
app = Flask(__name__)
CORS(app, resources={r"/*": {"origins": "*"}})  # 允许跨域请求（关键：前端才能调用接口）

# 日志配置
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 注册接口
@app.route("/register", methods=["POST"])
def register():
    try:
        data = request.json
        # 验证必填字段
        required_fields = ["username", "password", "real_name", "contact_info"]
        if not all(field in data for field in required_fields):
            return jsonify({"success": False, "error": "缺少必填字段"}), 400

        # 调用注册函数
        success = register_user(
            username=data["username"],
            password=data["password"],
            real_name=data["real_name"],
            contact_info=data["contact_info"],
            address=data.get("address", ""),  # 可选字段
            user_role=data.get("user_role", "买家")  # 默认为买家
        )
        return jsonify({"success": success})
    except Exception as e:
        logger.error(f"注册接口错误：{str(e)}")
        return jsonify({"success": False, "error": "服务器错误"}), 500

# 登录接口
@app.route("/login", methods=["POST"])
def login():
    try:
        data = request.json
        if not all(k in data for k in ["username", "password"]):
            return jsonify({"authenticated": False, "error": "缺少用户名或密码"}), 400

        # 验证用户
        authenticated = authenticate_user(data["username"], data["password"])
        return jsonify({"authenticated": authenticated})
    except Exception as e:
        logger.error(f"登录接口错误：{str(e)}")
        return jsonify({"authenticated": False, "error": "服务器错误"}), 500

# 获取用户信息接口（登录后用）
@app.route("/user", methods=["GET"])
def get_user():
    try:
        username = request.args.get("username")
        if not username:
            return jsonify(None)  # 用户名不存在返回空
        
        user = get_user_by_username(username)
        return jsonify(user)
    except Exception as e:
        logger.error(f"用户信息接口错误：{str(e)}")
        return jsonify(None), 500

# 发布艺术品接口
@app.route("/artwork", methods=["POST"])
def create_artwork_api():
    try:
        data = request.json
        required_fields = ["title", "price", "creator", "owner_id"]
        if not all(field in data for field in required_fields):
            return jsonify({"artwork_id": None, "error": "缺少必填字段"}), 400

        artwork_id = create_artwork(
            title=data["title"],
            description=data.get("description", ""),
            price=data["price"],
            creator=data["creator"],
            owner_id=data["owner_id"]
        )
        return jsonify({"artwork_id": artwork_id})
    except Exception as e:
        logger.error(f"发布艺术品接口错误：{str(e)}")
        return jsonify({"artwork_id": None, "error": "服务器错误"}), 500

# 获取所有艺术品接口
@app.route("/artworks", methods=["GET"])
def get_artworks():
    try:
        artworks = get_all_artworks()
        return jsonify(artworks)
    except Exception as e:
        logger.error(f"艺术品列表接口错误：{str(e)}")
        return jsonify([]), 500

if __name__ == "__main__":
    # 启动服务（默认端口5000，debug模式便于开发）
    app.run(debug=True, port=5000)
